package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"learn-land-crawler/app/config"
	"log"
	"time"
)

// DRIVER 指定驱动
const DRIVER = "mysql"

var db *gorm.DB

func InitDB() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?%s",
		config.MysqlConfig.Username,
		config.MysqlConfig.Password,
		config.MysqlConfig.Host,
		config.MysqlConfig.Port,
		config.MysqlConfig.Name,
		config.MysqlConfig.Params)

	gormLog := log.New(log.Default().Writer(), "GORM: ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
	newLogger := logger.New(
		gormLog, // io writer
		logger.Config{
			SlowThreshold: 500 * time.Millisecond,                      // 慢 SQL 阈值
			LogLevel:      logger.LogLevel(config.MysqlConfig.LogMode), // Log level
			Colorful:      true,                                        // 禁用彩色打印
		},
	)

	var err error
	conf := gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
		PrepareStmt: true,
		Logger:      newLogger,
	}
	db, err = gorm.Open(mysql.Open(dsn), &conf)
	if err != nil {
		log.Fatal(err)
	}

	// 初始化表结构
	autoMigrate()

	sqlDB, err := db.DB()
	if err != nil {
		log.Fatal(err)
	}
	sqlDB.SetMaxIdleConns(config.MysqlConfig.MaxIdle)
	sqlDB.SetMaxOpenConns(config.MysqlConfig.MaxOpen)
	sqlDB.SetConnMaxLifetime(time.Second * 300) //设置连接空闲超时

}

func GetDB() *gorm.DB {
	return db
}

func autoMigrate() {
	db.Set("gorm:table_options", "comment '标签' ").AutoMigrate(&Tag{})
	db.Set("gorm:table_options", "comment '爬虫的产品' ").AutoMigrate(&CProduct{})
	db.Set("gorm:table_options", "comment '产品标签' ").AutoMigrate(&ProductTag{})
	db.Set("gorm:table_options", "comment '图片转换后的产品' ").AutoMigrate(&TProduct{})
	db.Set("gorm:table_options", "comment '图片下载映射表' ").AutoMigrate(&TsPics{})
}
